﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Collections;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server;
using System.Web.UI;
using SearchAdminToolkit.Libary;

namespace SearchAdminToolkit.UI.Controls
{
    /// <summary>
    /// Defines a control for managing SharePoint Ranking Parameters.
    /// </summary>
    public class RankingParameterToolkitControl : BaseToolkitControl, INamingContainer
    {

        #region Fields

        private GridView _paramGrid;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the contained grid view of ranking parameters.
        /// </summary>
        private GridView ParamGrid
        {
            get
            {
                if (_paramGrid == null)
                {
                    _paramGrid = new GridView();
                }

                return _paramGrid;
            }
        }

        /// <summary>
        /// Gets the current sort order for the grid view.
        /// </summary>
        private SortDirection SortDirection
        {
            get
            {
                if (ViewState["_rankingParamSortDirection"] != null)
                {
                    return (SortDirection)ViewState["_rankingParamSortDirection"];
                }

                return SortDirection.Ascending;
            }
            set
            {
                ViewState["_rankingParamSortDirection"] = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Gets the section title.
        /// </summary>
        /// <returns></returns>
        protected override string GetSectionTitle()
        {
            return "Ranking Parameter Relevance Settings";
        }

        /// <summary>
        /// Gets the section description.
        /// </summary>
        /// <returns></returns>
        protected override string GetSectionDescription()
        {
            return "Use the table below to manage the ranking parameters to adjust relevance.<br /><br />";
        }

        /// <summary>
        /// Overridden to create this composite control.
        /// </summary>
        protected override void CreateChildControls()
        {

            this.InitializeRankingParamGrid();

            this.ParamGrid.RowEditing += new GridViewEditEventHandler(ParamGrid_RowEditing);
            this.ParamGrid.RowUpdating += new GridViewUpdateEventHandler(ParamGrid_RowUpdating);
            this.ParamGrid.Sorting += new GridViewSortEventHandler(ParamGrid_Sorting);
            this.ParamGrid.RowCancelingEdit += new GridViewCancelEditEventHandler(ParamGrid_RowCancelingEdit);
            this.ParamGrid.PageIndexChanging += new GridViewPageEventHandler(ParamGrid_PageIndexChanging);
            this.ParamGrid.Load += new EventHandler(ParamGrid_Load);

            this.Controls.Add(this.ParamGrid);

            base.CreateChildControls();
        }

        /// <summary>
        /// Overridden to render the composite control.
        /// </summary>
        /// <param name="writer"></param>
        protected override void RenderToolkitControl(System.Web.UI.HtmlTextWriter writer)
        {
            this.ParamGrid.RenderControl(writer);
        }

        /// <summary>
        /// Initializes the contained property grid.
        /// </summary>
        private void InitializeRankingParamGrid()
        {
            this.ParamGrid.AllowPaging = false;
            this.ParamGrid.AllowSorting = true;

            GridViewUtility.ApplyStyles(this.ParamGrid);

            this.ParamGrid.DataKeyNames = new string[] { "Name" };
            this.ParamGrid.Columns.Add(GridViewUtility.CreateEditCommandField());
            this.ParamGrid.Columns.Add(GridViewUtility.CreateBoundField("Rank Parameter", "Name", true));
            this.ParamGrid.Columns.Add(GridViewUtility.CreateBoundField("Value", "Value", false));

        }

        /// <summary>
        /// Binds the managed properties to the contained grid.
        /// </summary>
        private void BindRankingParamGrid()
        {
            try
            {
                this.ParamGrid.DataSource = RankingManager.FindAll();
                this.ParamGrid.DataBind();
            }
            catch (Exception e)
            {
                Page.Response.Write(e.Message);
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Responds to the event raised when the grid is loaded.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ParamGrid_Load(object sender, EventArgs e)
        {
            if (this.ParamGrid.Rows.Count == 0)
            {
                this.BindRankingParamGrid();
            }
        }

        /// <summary>
        /// Responds to the event raised when the page index changes.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ParamGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.ParamGrid.PageIndex = e.NewPageIndex;
            this.BindRankingParamGrid();
        }

        /// <summary>
        /// Responds to the event raised when the user cancels editing a row.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ParamGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.ParamGrid.EditIndex = -1;
            this.BindRankingParamGrid();
        }

        /// <summary>
        /// Responds to the event raised when a column is clicked for sorting.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ParamGrid_Sorting(object sender, GridViewSortEventArgs e)
        {
            this.ParamGrid.EditIndex = -1;

            IQueryable<RankingParameter> items = RankingManager.FindAll().AsQueryable<RankingParameter>();

            if (this.SortDirection == SortDirection.Ascending)
            {
                this.SortDirection = SortDirection.Descending;
                this.ParamGrid.DataSource = items.OrderBy(e.SortExpression).ToList<RankingParameter>();
            }
            else
            {
                this.SortDirection = SortDirection.Ascending;
                this.ParamGrid.DataSource = items.OrderBy(e.SortExpression).Reverse<RankingParameter>().ToList<RankingParameter>();
            }

            this.ParamGrid.DataBind();
        }

        /// <summary>
        /// Responds to the event raised when a row is being updated.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ParamGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridViewUtility.SynchronizeNewValues(e, this.ParamGrid);

                // **************** DevConnections Ranking Params

                // retrieve the ranking value and key of the ranking parameter property
                float value = Convert.ToSingle(e.NewValues["Value"]);

                if ((value < 0) || (value > 500))
                {
                    this.SetErrorMessage("The ranking value must be a value between 0 and 500.");
                }
                else
                {
                    string rankingParam = this.ParamGrid.DataKeys[e.RowIndex].Value.ToString();

                    // **************** DevConnections Ranking Params
                    RankingManager.Update(rankingParam, value);
                    // **************** DevConnections Ranking Params

                    // take the grid out of edit mode and rebind.
                    this.ParamGrid.EditIndex = -1;
                    this.BindRankingParamGrid();
                }

            }
            catch (Exception ex)
            {
                this.SetErrorMessage(string.Format("The following error occurred when attempting to update the ranking parameter: {0}", ex.Message));
            }
        }

        /// <summary>
        /// Responds to the event raised when a row is placed into edit mode.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ParamGrid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.ParamGrid.EditIndex = e.NewEditIndex;
            this.BindRankingParamGrid();
        }



        #endregion

    }
}
